package project.jpdftools.feedback;

import java.util.Properties;
import java.util.logging.Level;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import project.jpdftools.managers.LoggerManager;

public class SendEmail {

    private String userName;    // mail username
    private String password;    // mail password
    private String from;    // sender email
    private String to;      // receiver email
    private String fileAttachment;  // file to be attached
    private String mailSubject;     // subject of the email
    private String messageBody;     // body of the email

    /**
     * Constructor with parameters
     *
     * @param userName name of the mail user to connect with(used for
     * authentication)
     * @param password password of the mail to connect to(used for
     * authentication)
     * @param from sender email
     * @param to receiver email
     * @param fileAttachment file to be attached to the message
     * @param mailSubject subject of the email
     * @param messageBody body of the message
     */
    public SendEmail(String userName, String password, String from, String to, String fileAttachment, String mailSubject, String messageBody) {
        this.userName = userName;
        this.password = password;
        this.from = from;
        this.to = to;
        this.fileAttachment = fileAttachment;
        this.mailSubject = mailSubject;
        this.messageBody = messageBody;
    }

    /**
     * Sends an E-mail with a file attached to the required address
     */
    public boolean sendEmailWithAttachment() {
        try {
            // Get system properties
            Properties props = System.getProperties();

            // Setup mail server
            props.put("mail.smtp.host", "smtp.gmail.com");
            props.put("mail.smtp.socketFactory.port", "465");
            props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.port", "465");

            // Get session
            Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(userName, password);
                }
            });

            // Define message
            MimeMessage message = new MimeMessage(session);

            if (from.equals("") != true) {
                message.setFrom(new InternetAddress(from));
            } else {
                message.setFrom(new InternetAddress("Anonymous@Anonymous.com"));
            }

            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

            if (from.equals("") == true) {
                message.setSubject(mailSubject + " - Anonymous");
            } else {
                message.setSubject(mailSubject + " - " + from);
            }
            // create the message part
            MimeBodyPart messageBodyPart = new MimeBodyPart();

            //fill message
            messageBodyPart.setText(messageBody);

            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messageBodyPart);

            // Part two is attachment
            messageBodyPart = new MimeBodyPart();
            DataSource source = new FileDataSource(fileAttachment);
            messageBodyPart.setDataHandler(new DataHandler(source));
            messageBodyPart.setFileName(fileAttachment);
            multipart.addBodyPart(messageBodyPart);

            // Put parts in message
            message.setContent(multipart);

            // Send the message
            Transport.send(message);
            LoggerManager.getLogger().log(Level.INFO, "Email sent successfully.");
            return true;
        } catch (Exception ex) {
            LoggerManager.getLogger().log(Level.SEVERE, "Sending failed. Message = {0}", project.jpdftools.toolkit.Toolkit.getStackTraceAsString(ex.getCause()));
            return false;
        }
    }

    /**
     * Sends an E-mail to the required address
     */
    public boolean sendEmail() {
        try {
            // Get system properties
            Properties props = System.getProperties();

            // Setup mail server
            props.put("mail.smtp.host", "smtp.gmail.com");
            props.put("mail.smtp.socketFactory.port", "465");
            props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.port", "465");

            // Get session
            Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(userName, password);
                }
            });

            // Define message
            MimeMessage message = new MimeMessage(session);
            if (from.equals("") != true) {
                message.setFrom(new InternetAddress(from));
            } else {
                message.setFrom(new InternetAddress("Anonymous@Anonymous.com"));
            }
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            if (from.equals("") == true) {
                message.setSubject(mailSubject + " - Anonymous");
            } else {
                message.setSubject(mailSubject + " - " + from);
            }

            //fill message
            message.setText(messageBody);

            // Send the message
            Transport.send(message);
            LoggerManager.getLogger().log(Level.INFO, "Email sent successfully.");
            return true;
        } catch (Exception ex) {
            LoggerManager.getLogger().log(Level.SEVERE, "Sending failed. Message = {0}", project.jpdftools.toolkit.Toolkit.getStackTraceAsString(ex.getCause()));
            return false;
        }
    }
}
